/*
 * SensorSampler.java
 *
 * Copyright (c) 2008 Sun Microsystems, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */


package org.sunspotworld;

import com.sun.spot.sensorboard.EDemoBoard;
import com.sun.spot.sensorboard.io.IScalarInput;
import com.sun.spot.io.j2me.radiogram.*;
import com.sun.spot.sensorboard.peripheral.ITemperatureInput;
import com.sun.spot.sensorboard.peripheral.ITriColorLED;
import com.sun.spot.sensorboard.peripheral.LEDColor;
import com.sun.spot.util.Utils;
import javax.microedition.io.*;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import com.sun.spot.sensorboard.capabilities.IGPIOController;
import com.sun.spot.sensorboard.io.IIOPin;
import com.sun.spot.sensorboard.io.IOutputPin;
import com.sun.spot.sensorboard.peripheral.ISwitch;
import java.io.IOException;


/**
 * This application is the 'on SPOT' portion of the SendDataDemo. It
 * periodically samples a sensor value on the SPOT and transmits it to
 * a desktop application (the 'on Desktop' portion of the SendDataDemo)
 * where the values are displayed.
 *
 * @author: Vipul Gupta
 * modified: Ron Goldman
 */
public class SensorSampler extends MIDlet {

    private static final int HOST_PORT = 67;
    private static final int HOST_PORT_2 = 68;
    private static final int SAMPLE_PERIOD = 10 * 1000;  // in milliseconds
    
    protected void startApp() throws MIDletStateChangeException {
        RadiogramConnection rConR = null;
        RadiogramConnection rConE = null;
        Datagram dgE = null;
        Datagram dgR = null;
        int selectedSpot = 1;
        int selectedSensor = 1;
        String ourAddress = System.getProperty("IEEE_ADDRESS");
        long now = 0L;
        IScalarInput lightSensor =  EDemoBoard.getInstance().getLightSensor();
        ITemperatureInput tempSensor = EDemoBoard.getInstance().getADCTemperature();
        int reading = 0;
        ITriColorLED[] leds = EDemoBoard.getInstance().getLEDs();
        IOutputPin outs[] = EDemoBoard.getInstance().getOutputPins();
        IOutputPin ins = EDemoBoard.getInstance().getOutputPins()[EDemoBoard.H0];
        ISwitch sw1 = EDemoBoard.getInstance().getSwitches()[0];  
        ISwitch sw2 = EDemoBoard.getInstance().getSwitches()[1];  
        
        
        
        System.out.println("Starting sensor sampler application on " + ourAddress + " ...");
        new com.sun.spot.util.BootloaderListener().start();       // Listen for downloads/commands over USB connection
        try {
            // Open up a broadcast connection to the host port
            // where the 'on Desktop' portion of this demo is listening
            rConE = (RadiogramConnection) Connector.open("radiogram://broadcast:" + HOST_PORT);
            dgE = rConE.newDatagram(50);  // only sending 12 bytes of data
        } catch (Exception e) {
            System.err.println("Caught " + e + " in connection initialization.");
            System.exit(1);
        }
        
        try {
            // Open up a server-side broadcast radiogram connection
            // to listen for sensor readings being sent by different SPOTs
            rConR = (RadiogramConnection) Connector.open("radiogram://:" + HOST_PORT_2);
            dgR = (Radiogram)rConR.newDatagram(rConR.getMaximumLength());
        } catch (Exception e) {
             System.err.println("Receive caught " + e.getMessage());
        }
        
        leds[0].setColor(LEDColor.ORANGE); 
            leds[1].setColor(LEDColor.ORANGE); 
            leds[2].setColor(LEDColor.ORANGE); 
            leds[6].setColor(LEDColor.BLUE);
            leds[7].setColor(LEDColor.BLUE);
            leds[6].setOn();
            leds[0].setOn();
        
        while (true) {
            if (sw1.isClosed()){
                System.out.println("Spot changed to: "+(selectedSpot+1));
                if (selectedSpot == 3){
                    selectedSpot = 1;
                } else {
                    selectedSpot++;
                }
             
                
                if (selectedSpot == 1){
                    leds[0].setOn();
                    leds[1].setOff();
                    leds[2].setOff();
                } else if (selectedSpot == 2){
                    leds[0].setOn();
                    leds[1].setOn();
                    leds[2].setOff(); 
                } else if (selectedSpot == 3){
                    leds[0].setOn();
                    leds[1].setOn();
                    leds[2].setOn(); 
                }  
            }
            if (sw2.isClosed()){
                System.out.println("Spot sensor changed to: "+(selectedSensor+1));
                if (selectedSpot == 1){
                        if (selectedSensor == 2){
                            selectedSensor = 1;
                        } else {
                            selectedSensor++;
                        }
                    
                        if (selectedSensor == 1){
                            leds[6].setOn();
                            leds[7].setOff();
                        }else if (selectedSensor == 2){
                            leds[6].setOff();
                            leds[7].setOn();
                        }    
                }
            }
            
            try {
                if ((rConR.packetsAvailable() == true) && (selectedSpot > 1)){
                    rConR.receive(dgR);
                    int tipoSpot = dgR.readInt();         // read the sensor value
                    int pin = dgR.readInt();
                    int action = dgR.readInt();
                    
                    System.out.println("RECIBI: "+tipoSpot+pin+action);
        
                    if ((tipoSpot == 2) && (tipoSpot == selectedSpot)){
                        if (pin == 0) {
                            if (action == 1){
                                outs[EDemoBoard.H0].setHigh();
                            } else{
                                outs[EDemoBoard.H0].setLow();
                            }
                        }else if (pin == 1) {
                            if (action == 1){
                                outs[EDemoBoard.H1].setHigh();
                            } else{
                                outs[EDemoBoard.H1].setLow();
                            }
                        }else if (pin == 2) {
                            if (action == 1){
                                outs[EDemoBoard.H2].setHigh();
                            } else{
                                outs[EDemoBoard.H2].setLow();
                            }
                        }else if (pin == 3) {
                            if (action == 1){
                                outs[EDemoBoard.H3].setHigh();
                            } else{
                                outs[EDemoBoard.H3].setLow();
                            }
                        }
                    }else if ((tipoSpot == 3)&& (tipoSpot == selectedSpot)){
                        if (pin == 0) {
                            if (action == 1){
                                outs[EDemoBoard.H0].setHigh();
                            } else{
                                outs[EDemoBoard.H0].setLow();
                            }
                        }else if (pin == 1) {
                            if (action == 1){
                                outs[EDemoBoard.H1].setHigh();
                            } else{
                                outs[EDemoBoard.H1].setLow();
                            }
                        }else if (pin == 2) {
                            if (action == 1){
                                outs[EDemoBoard.H2].setHigh();
                            } else{
                                outs[EDemoBoard.H2].setLow();
                            }
                        }else if (pin == 3) {
                            if (action == 1){
                                outs[EDemoBoard.H3].setHigh();
                            } else{
                                outs[EDemoBoard.H3].setLow();
                            }
                        }
                    }
                }
            } catch (IOException ex) {
                ex.printStackTrace();
                System.out.println("Error recibiendo");
            }
         
            try {
                
                if (selectedSpot == 1){
                    
                    now = System.currentTimeMillis();
                    if (selectedSensor == 1){
                        reading = lightSensor.getValue();
                        leds[6].setColor(LEDColor.GREEN); 
                        dgE.reset();
                        dgE.writeLong(now);
                        dgE.writeInt(reading);
                        dgE.writeInt(1);
                        System.out.println("Light value = " + reading);
                        Utils.sleep(1000);
                        leds[6].setColor(LEDColor.BLUE);
            
                    } else if (selectedSensor == 2){
                        reading = (int) tempSensor.getCelsius();
                        leds[7].setColor(LEDColor.GREEN); 
                        dgE.reset();
                        dgE.writeLong(now);
                        dgE.writeInt(reading);
                        dgE.writeInt(2);
                        System.out.println("Temp value = " + reading);
                        Utils.sleep(1000);
                        leds[7].setColor(LEDColor.BLUE);
                    }
                    //Utils.sleep(SAMPLE_PERIOD - (System.currentTimeMillis() - now));
                    
                }
            } catch (Exception e) {
                System.err.println("Caught " + e + " while collecting/sending sensor sample.");
            }
            if (selectedSpot == 1){
                try {
                    rConE.send(dgE);
                    Utils.sleep(1000);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }else{
                Utils.sleep(100);
            }
                
        }
    }
    
    protected void pauseApp() {
        // This will never be called by the Squawk VM
    }
    
    protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
        // Only called if startApp throws any exception other than MIDletStateChangeException
    }
}
